// 函数组件
import { ExclamationCircleFilled } from "@ant-design/icons";
import { Button, ConfigProvider, Form, Input, message, Modal, Table } from "antd";
import zh_CN from "antd/es/locale/zh_CN";
import type { ColumnsType } from "antd/es/table";
import type { TableRowSelection } from "antd/es/table/interface";
import { useEffect, useState } from 'react';
import "../../../../src/App.css";
import { adduser, cancel, modificationLabel, Usertags } from "../../../api/userApi"; //引入结构接口
import "./userCss/UserLabel.less";

function UserLabel() {
  const { confirm } = Modal;
  const [form] = Form.useForm();
  const [form1] = Form.useForm();
  const [amend,setAmend] = useState(Object);//装修改内容
  const [data, setData] = useState<DataType[]>([]);
  interface DataType {
    tnumber?: number;
    tid:number
    tname?: string;
    tcondition?: string;
  }

  let flag;
  // 表格列
  const columns: ColumnsType<DataType> = [
    {
      title: "序号",
      dataIndex: "tid",
      width: "7%",
      align: "center",
    },
    {
      title: "标签名称",
      dataIndex: "tname",
      align: "center",
    },
    {
      title: "用户人数",
      dataIndex: "tnumber",
      align: "center",
    },
    {
      title: "标签条件",
      dataIndex: "tcondition",
      align: "center",
    },
    {
      title: "操作",
      dataIndex: "operation",
      align: "center",
      width: "20%",
      render: (value, record) => (
        <div>
          {/* <button className="one">添加</button> */}
          <button className="edit"   onClick={() =>{
            showModal(record)
            }}>编辑</button>
          <button className="del"  onClick={() =>{
              showPromiseConfirm(record);
            }}>删除</button>
        </div>
      ),
    },
  ];

  // 表格数据
  useEffect(() => {
    getUserData();
  }, []);
  // 获取数据
  const getUserData = async () => {
    try {
      let res = await Usertags();
      // console.log('进入了res');
      if (res.code == "200") {
        console.log("1111111", res);
        setData(res.data);
      }
    } catch (err) {
      console.log(err);
    }
  };
  
  
  // 删除
  const showPromiseConfirm = (record:any) => {
    console.log('打印传输的数据',record);
    confirm({
      title: "确认删除此信息",
      icon: <ExclamationCircleFilled />,
      content: "删除该数据",
      onOk() {
        cancel(
          {tId:record.tid}
        ).then(res=>{
          console.log(res);
          if (Number(res.code)  === 200) {
           message.success('删除成功！')
           getUserData()
           } else {
            message.info('删除失误啦！')
            }
          }).catch(err => {
            console.log('err错误了哟', err);
        })
      },
      onCancel() {},
    });
  };

// 修改弹框初始值设置
useEffect(()=>{
  form.setFieldsValue({
    // tid:amend.tid,
     name:amend.tname,
      detailed:amend.tcondition,
  })
  // console.log('gengg',amend);
},[amend])
//编辑
const [isModalOpen, setIsModalOpen] = useState(false);
// 添加
const [isModalOpen1, setIsModalOpen1] = useState(false);
  // 编辑函数
    const showModal = (record: any) => {
      setAmend(record)
      setIsModalOpen(true);
      
    };
    const handleOk = (val:any) => {
      console.log(val,amend.tid);
      modificationLabel({
        tid: amend.tid,
        tname:val.name,
        tcondition: val.detailed,
      }).then(res=>{
        message.success('修改成功！')
        getUserData()
      }).catch(err=>{
        console.log('err',err);
      })
      setIsModalOpen(false);
    };
  
    const handleCancel = () =>{
      setIsModalOpen(false);
    };

    //添加
    const handleOk1 = (val:any) => {
      console.log(val,amend.tid);
      adduser({
        // tid: val.tid,
        tname:val.name1,
        tcondition: val.detailed1,

      }).then(res=>{
        message.success('添加成功')
        getUserData()
      }).catch(err=>{
        console.log('err',err);
      })
      setIsModalOpen1(false);
    }
    const handleCancel1 = () =>{
      setIsModalOpen1(false);
    };
    //添加弹框
    const handleAdd = () =>{
      setIsModalOpen1(true);
    };

  const rowSelection: TableRowSelection<DataType> = {
    // selectedRowKeys,
    // onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: "odd",
        text: "Select Odd Row",
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          // setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: "even",
        text: "Select Even Row",
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          // setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };

  return (
    // <div className='UserLabel'>
    //     用户标签
    // </div>

    <div className="UserLabel">
      {/* 头部 */}
      <div className="page-top">
        {/* 左边标题 */}
        <div className="page-title">
          <p>标签列表</p>
        </div>
      </div>

      <div className="page-context">
        {/* 表格部分 */}
        <div className="data-list">
          {/* 表格部分 */}
          <div className="information">
          <p>数据列表</p>
          {/* 添加 */}
          <button className="add" onClick={handleAdd}>添加</button>
          </div>
          
          <ConfigProvider locale={zh_CN}>
            <Table
              rowSelection={rowSelection}
              columns={columns}
              dataSource={data}
              scroll={{ y: 270 }}
              rowKey={(item) => item.tid}
              pagination={{
                position: ["bottomCenter"],
                defaultPageSize: 10,
                pageSizeOptions: [3, 5, 10, 15],
                showQuickJumper: true,
                showSizeChanger: true,
              }}
            />
          </ConfigProvider>
        </div>
      </div>
      <Modal title="编辑" open={isModalOpen} onCancel={handleCancel}  footer={null} forceRender={true}>
      <Form
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 16 }}
          layout="horizontal"
          style={{ maxWidth: 600 }}
          autoComplete="off"
          form={form} onFinish={handleOk}
        >
          <Form.Item label="标签名称" name='name'   >
            <Input placeholder="请输入标签名称" />
          </Form.Item>
          <Form.Item label="标签条件" name='detailed'  >
            <Input placeholder="请输标签条件" />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }} className='opreate'>
            <Button type="primary" htmlType="submit" className='submit'>提交</Button>
            <Button type="primary" onClick={handleCancel} className='cancel'>取消</Button>
          </Form.Item>
        </Form>                      
      </Modal>
      {/* 添加 */}
      <Modal title="添加" open={isModalOpen1} onCancel={handleAdd} footer={null}  forceRender={true}>
      <Form
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 16 }}
          layout="horizontal"
          style={{ maxWidth: 600 }}
          autoComplete="off"
          form={form1} onFinish={handleOk1}
        >
          <Form.Item label="标签名称" name='name1'   >
            <Input placeholder="" />
          </Form.Item>
          <Form.Item label="标签条件" name='detailed1'  >
          <Input addonAfter="笔"  />
          </Form.Item>
          {/* <Form.Item label="或者" name='detailed1'  >
          <Input addonAfter="元"  />
          </Form.Item> */}
          <Form.Item wrapperCol={{ offset: 8, span: 16 }} className='opreate'>
            <Button type="primary" htmlType="submit" className='submit'>提交</Button>
            <Button type="primary" onClick={handleCancel1} className='cancel'>取消</Button>
          </Form.Item>
        </Form>                      
      </Modal>
    </div>
  );
}

export default UserLabel;
